package com.party.system.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Base64;

/**
 * @FileName: kcsm
 * @author: 王晨旭
 * @date: 2025/3/12 11:34
 * @Description:
 */
public class PosterGeneration {


    public static String generate(String backgroundImg,String title,String kcId) throws IOException, WriterException {
        int width = 400;
        int height = 600;
        int cornerRadius = 10; // 圆角半径
        System.out.println("===================1=====================================");

        // 创建空白海报
        BufferedImage poster = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = poster.createGraphics();
        System.out.println("===================2=====================================");

        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 创建圆角剪裁区域
        RoundRectangle2D roundedRect = new RoundRectangle2D.Float(0, 0, width, height, cornerRadius, cornerRadius);
        g2d.setClip(roundedRect);
        System.out.println("===================3=====================================");
        // 背景颜色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);

        System.out.println("===================4=====================================");
        BufferedImage headImg = ImageIO.read(new File(backgroundImg));
        // 读取背景图片（支持网络和本地）
        try {
            BufferedImage bgImage;
            if (backgroundImg.startsWith("http://") || backgroundImg.startsWith("https://")) {
                bgImage = ImageIO.read(new URL(backgroundImg));  // 读取网络图片
            } else {
                bgImage = ImageIO.read(new File(backgroundImg)); // 读取本地图片
            }

            BufferedImage roundedBg = createRoundedImage(bgImage, width - 60, height - 300, cornerRadius);
            g2d.drawImage(roundedBg, 8, 8, width - 15, height - 250, null);
        } catch (IOException e) {
            System.err.println("背景图片加载失败，使用默认白色背景：" + e.getMessage());
        }
        System.out.println("===================5=====================================");
        // 设置字体
        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font("微软雅黑", Font.BOLD, 28));
        g2d.drawString(title, 8, height - 180);

        // 生成二维码
        String accessToken = WxQRCodeGeneration.getAccessToken();
        String property = System.getProperty("user.dir");
        property = property.replace("\\", "/");
        byte[] imageBytes = WxQRCodeGeneration.generateWxCode(accessToken, "pages/zhenxuan/soursedeatil/soursedeatil?id="+kcId, property+"/xxx.png");
        ByteArrayInputStream qrCode = new ByteArrayInputStream(imageBytes);
        BufferedImage read = ImageIO.read(qrCode);
        g2d.drawImage(read, width - 130, height - 150, 100, 100, null);
        // 获取resources 目录下的logo 图片
        System.out.println("===================6=+"+property+"====================================");
        BufferedImage logoImage = ImageIO.read(new File(property+"/logo.png"));
        g2d.drawImage(logoImage, 20, height - 150, 100, 100, null);
        System.out.println("===================7=====================================");

        // 添加品牌标识
//        g2d.setColor(Color.BLUE);
//        g2d.setFont(new Font("微软雅黑", Font.BOLD, 24));
//        g2d.drawString("升维智选", 50, height - 120);
//        g2d.setFont(new Font("微软雅黑", Font.PLAIN, 18));
//        g2d.drawString("升维思考  精准行动", 50, height - 90);
        g2d.dispose();
        // 返回  base64Image
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(poster, "png", outputStream);
        String base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());
        return base64Image;
    }
    // 生成二维码的方法
    public static BufferedImage generateQRCodeImage(String text, int width, int height) throws WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

    // 生成圆角背景图片
    public static BufferedImage createRoundedImage(BufferedImage image, int targetWidth, int targetHeight, int radius) {
        BufferedImage output = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = output.createGraphics();

        // 开启抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

        // 创建圆角剪裁区域
        RoundRectangle2D roundedRect = new RoundRectangle2D.Float(0, 0, targetWidth, targetHeight, radius, radius);
        g2.setClip(roundedRect);

        // 调整并绘制背景图
        g2.drawImage(image, 0, 0, targetWidth, targetHeight, null);
        g2.dispose();

        return output;
    }

}
